<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="success" @click="addclick">添加</el-button>
        <el-button type="danger" @click="handleDeleteArray">批量删除</el-button>
        <el-button type="primary" @click="toggleSelection(data.petMessage)">全选</el-button>
        <el-input
            v-model="state.query"
            class="searchInput"
            placeholder="宠物名"
            :prefix-icon="Search"
            @change="handleChange"
            @clear="handleClear"
        />
        <el-button :icon="Search" @click="handleChange"/>
        <!--    新增功能的对话框     -->
        <el-dialog v-model="dialogFormVisible"
                   title="宠物信息建档"
                   width="700"
                   :destroy-on-close="true"
                   @close="handleClose"
                   draggable
        >
          <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item label="宠物名字" prop="pet_name" label-width="80">
              <el-input v-model="form.pet_name" autocomplete="off" placeholder="请输入宠物的名字"/>
            </el-form-item>
            <el-form-item label="宠物性别" prop="pet_sex" label-width="80">
              <el-select v-model="form.pet_sex" placeholder="请选择宠物的性别">
                <el-option
                    v-for="item in option1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="宠物年龄" prop="pet_age" label-width="80">
              <el-input type="float" v-model="form.pet_age" autocomplete="off" placeholder="请输入宠物的年龄"/>
            </el-form-item>
            <el-form-item label="宠物种类" prop="pet_kind" label-width="80">
              <el-select v-model="form.pet_catagory" placeholder="请选择宠物的种类">
                <el-option
                    v-for="item in option4"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="宠物品种" prop="pet_kind" label-width="80">
              <el-input v-model="form.pet_kind" autocomplete="off" placeholder="请输入宠物的种类"/>
            </el-form-item>
            <el-form-item label="宠物健康程度" prop="pet_healthy" label-width="108">
              <el-select v-model="form.pet_healthy" placeholder="根据医生的判断填写">
                <el-option
                    v-for="item in option2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上传宠物照片" prop="fileList" label-width="100">
              <el-upload
                  action="http://127.0.0.1:8000/admincharge/petmsg/uploadmessage/"
                  list-type="picture-card"
                  :auto-upload="true"
                  ref="pictureUpload"
                  :headers="uploadHeaders"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :limit="3"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                    <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in/></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete/></el-icon>
          </span>
        </span>
                  </div>
                </template>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="form.fileList" alt="Preview Image"/>
              </el-dialog>
            </el-form-item>
            <el-form-item label="注射疫苗情况" prop="pet_vaccines" label-width="120">
              <el-select v-model="form.pet_vaccines" placeholder="询问之前是否注射过疫苗">
                <el-option
                    v-for="item in option3"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上一次接种时间" prop="pet_vaccinestime" label-width="130">
              <el-date-picker
                  v-model="form.pet_vaccinestime"
                  type="date"
                  placeholder="请选择时间"
                  :disabled-date="disabledDate"
                  :shortcuts="shortcuts"
                  size="default"
              />
            </el-form-item>
            <el-form-item label="建档账号" prop="apply_account" label-width="80">
              <el-input v-model="form.apply_account"/>
            </el-form-item>
            <el-form-item label="补充其他" prop="description" label-width="80">
              <el-input v-model="form.description" rows="4" type="textarea"/>
            </el-form-item>
          </el-form>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" v-loading="loading" @click="handleSubmit">提交</el-button>
      </span>
          </template>
        </el-dialog>
      </div>
    </template>
    <!--    展示表格     -->
    <el-table
        ref="multipleTableRef"
        :data="data.petMessage"
        style="width: 100%;font-size: 19px"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
        empty-text="当前没有数据"
        height="680"
    >
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="id" label="序号" width="55" align="center"/>
      <el-table-column prop="petname" label="宠物名字" width="100" align="center"/>
      <el-table-column prop="petage" label="宠物年龄" width="100" show-overflow-tooltip align="center"/>
      <el-table-column prop="petkind" label="宠物品种" width="100" show-overflow-tooltip align="center"/>
      <el-table-column prop="petcatagory" label="宠物种类" width="100" show-overflow-tooltip align="center"/>
      <el-table-column prop="petsex" label="宠物性别" width="100" show-overflow-tooltip align="center"
                       :formatter="petSexFormatter"/>
      <el-table-column prop="petvaccines" label="上次注射疫苗情况" width="120" show-overflow-tooltip align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.petvaccines === 1" type="success">已接种</el-tag>
          <el-tag v-else type="danger">未接种</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="petvaccinestime" label="注射疫苗时间" width="200" show-overflow-tooltip align="center"/>
      <el-table-column prop="healthy" label="健康程度" width="100" show-overflow-tooltip align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.healthy === 1" type="success">健康</el-tag>
          <el-tag v-else-if="scope.row.healthy === 2" type="warning">少许疾病</el-tag>
          <el-tag v-else-if="scope.row.healthy === 3" type="danger">重大疾病</el-tag>
          <el-tag v-else-if="scope.row.healthy === 4" type="primary">残疾</el-tag>
          <el-tag v-else type="info">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="imagesurl" label="宠物图片" width="150" show-overflow-tooltip align="center">
        <template #default="scope">
          <div>
            <el-image
                fit="cover"
                :src="scope.row.imagesurl"
                :preview-src-list="[scope.row.imagesurl]"
                style="width: 90px; height: 90px"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :initial-index="1"
                preview-teleported="true"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="apply_account" label="建档账号" width="200" show-overflow-tooltip align="center"/>
      <el-table-column prop="description" label="其余补充" width="450" show-overflow-tooltip align="center"/>
      <el-table-column label="操作" width="225" show-overflow-tooltip align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-popconfirm title="是否确定要删除吗" confirm-button-text="是" cancel-button-text="否"
                         @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
              >删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background
                   layout="prev, pager, next"
                   :total="state.total"
                   :page-sizes="[10, 20, 30, 50]"
                   :page-size="state.pageSize"
                   :current-page="state.page"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup>
// 接收后端传过来的数据
import {
  GetPetMessageService,
  AddMessageService,
  deleteNoticeUrlService,
  deleteNoticeUrlsService,
  editMessageService
} from '@/api/petmessage.js'
import {onMounted, reactive, ref, nextTick} from 'vue'
import {Delete, Download, Plus, ZoomIn, Search} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

// 获取所有列表信息
const multipleTableRef = ref()
const data = reactive({
  petMessage: [],
})
const getPetList = () => {
  GetPetMessageService(state)
      .then((res) => {
        loading.value = false
        // console.log(res.data.data)
        data.petMessage = res.data.results.data
        console.log('拿到了吗', data.petMessage)
        state.total = res.data.count
      })
      .catch((error) => {
        data.loading = false
        console.log(error)
      })
}
// 列表枚举值转义(petsex)
const petSexFormatter = (form) => {
  if (form.petsex == 1) {
    return '公'
  }
  if (form.petsex == 2) {
    return '母'
  }
}

onMounted(() => {
  getPetList()
})
// 加载中
const loading = ref(true)

// 新增的对话框
const dialogFormVisible = ref(false)

// 表单引用，全部验证
const formRef = ref()
const rules = reactive({
  pet_name: [
    {required: true, message: '请输入宠物的名字，以便主人辨认', trigger: 'blur'}
  ],
  pet_sex: [
    {required: true, message: '请选择宠物的性别', trigger: 'change'}
  ],
  pet_age: [
    {required: true, message: '请输入宠物的年龄', trigger: 'blur'}
  ],
  pet_catagory: [
    {required: true, message: '请选择宠物的品种', trigger: 'blur'}
  ],
  pet_kind: [
    {required: true, message: '请填写宠物的种类', trigger: 'blur'}
  ],
  pet_healthy: [
    {required: true, message: '请选择宠物的健康程度', trigger: 'change'}
  ],
  pet_vaccines: [
    {required: true, message: '请填写上一次是否注射了疫苗', trigger: 'blur'}
  ],
  pet_vaccinestime: [
    {required: true, type: 'date', message: '请选择上次注射疫苗的大致时间', trigger: 'change'}
  ]
})
// 点击添加对话框
const addclick = () => {
  dialogFormVisible.value = true
  formTitle.value = '宠物建档'
}
// 下拉框的label和value值
const option1 = [
  {value: '1', label: '公'},
  {value: '2', label: '母'}
]
const option4 = [
  {value: '狗', label: '狗'},
  {value: '猫', label: '猫'}
]
const option2 = [
  {value: '1', label: '健康'},
  {value: '2', label: '少许疾病'},
  {value: '3', label: '重大疾病'},
  {value: '4', label: '残疾'},
  {value: '5', label: '其他'}
]
const option3 = [
  {value: '1', label: '已接种'},
  {value: '2', label: '未接种'},
]

// 添加对话框里面的时间选择器
const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 表单处理
const form = ref({
  pet_name: '',
  pet_sex: '',
  pet_age: '',
  pet_kind: '',
  pet_healthy: '',
  fileList: '',
  pet_vaccines: '',
  pet_vaccinestime: '',
  apply_account:'',
  description: ''
})
// 对话框题目
const formTitle = ref('')
// ---------------------------------------------------
// 处理图片
const dialogVisible = ref(false)
const disabled = ref(false)
const pictureUpload = ref('')
const uploadHeaders = ref({
  Authorization: 'bearer' + ' ' + localStorage.getItem('admin_token')
})

const handleRemove = () => {
  pictureUpload.value.clearFiles()
}

const handlePictureCardPreview = (file) => {
  form.value.fileList = file.url
  dialogVisible.value = true
  // console.log(file)
}

const handleAvatarSuccess = async (response, file) => {
  console.log(file)
  form.value.fileList = response['0']
  console.log('图片的地址', form.value.fileList)
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpg" && rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    console.log(rawFile)
    ElMessage.error('文件格式必须是jpg、jpeg或者png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('该文件格式不能超过 20MB!')
    return false
  }
  return true
}
// 点击提交前做个验证
const handleSubmit = () => {
  if (formTitle.value == '宠物建档') {
    console.log('开始建档')
    pictureUpload.value.submit()
    formRef.value?.validate().then(() => {
      commitMsg()
      setTimeout(() => {
        getPetList()
      }, 1000)
    }).catch(() => {
      ElMessage.error('不能为空')
    })
  } else {
    console.log('开始编辑')
    pictureUpload.value.submit()
    formRef.value?.validate().then(() => {
      saveEdit()
      setTimeout(() => {
        getPetList()
      }, 1000)
    }).catch(() => {
      ElMessage.error('不能为空')
    })
  }

}
// 上传对话框的数据
const commitMsg = async () => {
  console.log('发送数据里面的formvalue', form.value)
  await AddMessageService(form.value)
      .then((res) => {
        loading.value = false
        dialogFormVisible.value = false
        ElMessage.success('发送成功')
        console.log("请求里面的res", res)
      }).catch((error) => {
        loading.value = false
        ElMessage.error(error)
        console.log(error)
      })
}
// 关闭回调清空对话框里面的数据和校验规则
const handleClose = () => {
  formRef.value.resetFields()
  formRef.value.clearValidate()
}


// 单个删除组件
const handleDelete = (row) => {
  const params = row.id;
  deleteNoticeUrlService(params).then((res) => {
    console.log(res.data);
    getPetList()
  });
};

// 全选
const multipleSelection = ref([]);
const toggleSelection = (rows) => {
  if (rows) {
    console.log(rows)
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
}
// 监听行的状态变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 批量删除
const handleDeleteArray = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning('麻烦你选中了再点')
  }
  for (var i = 0; i < multipleSelection.value.length; i++) {
    const params = multipleSelection.value[i].id;
    const Ids = []
    Ids.push(...multipleSelection.value.map(row => row.id))
    console.log(Ids, params);
    deleteNoticeUrlsService({Ids: Ids})
        .then((res) => {
          multipleSelection.value = []
          console.log(res.data);
          getPetList()
        });
  }
}

// 分页和搜索关键字
const state = reactive({
  query: '',   //搜索关键字
  page: 1, //当前页的索引
  total: 0,  //总长度
  pageSize: 10,   //每页记录的条数
})
// 关键字搜索框
const handleChange = () => {
  const res = getPetList()
  console.log('找到了吗', res)
}

const handleSizeChange = (size) => {
  state.pageSize = size
  getPetList()
}
const handleCurrentChange = (current) => {
  state.page = current
  getPetList()
}
// 编辑对话框
const handleEdit = (index, row) => {
  dialogFormVisible.value = true
  formTitle.value = '开始编辑'
  // console.log(index, row.petsex)
  nextTick(() => {
    form.value.pet_name = row.petname
    form.value.pet_age = row.petage
    form.value.pet_kind = row.petkind
    form.value.fileList = row.imagesurl
    form.value.pet_vaccinestime = row.petvaccinestime
    form.value.description = row.description
    form.value.apply_account = row.apply_account
    form.value.id = row.id
  })
  console.log(row.imagesurl)
}
// 保存编辑
const saveEdit = async () => {
  try {
    const data = {
      id: form.value.id,
      petname: form.value.pet_name,
      petsex: form.value.pet_sex,
      petage: form.value.pet_age,
      petkind: form.value.pet_kind,
      healthy: form.value.pet_healthy,
      fileList: form.value.fileList,
      petvaccines: form.value.pet_vaccines,
      petvaccinestime: form.value.pet_vaccinestime,
      apply_account:form.value.apply_account,
      description: form.value.description
    }
    const res = await editMessageService(data)
    console.log(res.data)
    dialogFormVisible.value = false
    getPetList()
  } catch (error) {
    console.log(error)
  }
}

</script>
<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.searchInput {
  width: 350px;
  height: 37px;
  margin-left: 20px;
}
</style>